import os
from kubernetes import client, config

class K8sClinet():
    """
    install  pip install kubernetes
    doc https://github.com/kubernetes-client/python

    config 参数是个文件，是k8s主节点下的/root/.kube/config

    """
    def __init__(self,config):
        self.config = config
        try:
            self.k8s_config = self.config
        except Exception as e:
            self.k8s_config = "config"
        self.conn_api_instance = self._conn_api_instance() #扩展api
        self.conn_v1 = self._conn_v1() #核心api

    def _conn_api_instance(self):
        config.kube_config.load_kube_config(config_file=self.k8s_config)
        api_instance = client.AppsV1Api(client.ApiClient())
        return api_instance

    def _conn_v1(self):
        config.kube_config.load_kube_config(config_file=self.k8s_config)
        v1 = client.CoreV1Api()
        return v1

    def read_namespaced_deployment_scale(self,name,namespaces):
        return self.conn_api_instance.read_namespaced_deployment_scale(name,namespaces)

    def get_replicas_namespaced_deployment_scale(self,name,namespaces):
        rnds = self.read_namespaced_deployment_scale(name,namespaces)
        return rnds.spec.replicas

    def set_replicas_namespaced_deployment_scale(self,name,namespaces,replicas_number):
        replicas_number = int(replicas_number)
        rnds = self.read_namespaced_deployment_scale(name,namespaces)
        rnds.spec.replicas = replicas_number
        return self.patch_namespaced_deployment_scale(name,namespaces,body=rnds)

    def patch_namespaced_deployment_scale(self,name,namespaces,body):
        return self.conn_api_instance.patch_namespaced_deployment_scale(name,namespaces,body)



if __name__ == '__main__':
    k8sclient = K8sClinet("/root/.kube/config")
    #伸缩命名空间a的b应用为2个副本
    set2 = k8sclient.set_replicas_namespaced_deployment_scale("b","a",2)
    print(set2)
    #读取a命名空间的b的副本节点数
    #r1 = k8sclient.read_namespaced_deployment_scale("b","a")
    #print(r1)